# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import datetime
import hashlib
import json
import logging
import time

import requests
from django.utils import timezone

from wlviews.apis.models import ELFBlog, ELWmylog

add_log = logging.getLogger('error')


# 风报api类
class FBAPI(object):
    the_key = "Zn0rLhy0M5kAAQ"
    the_host = "http://data.riskstorm.com/v1/"
    regno = ""

    def __init__(self, regno):
        self.regno = regno

    def __str__(self):
        return 'FB API'

    # 事件接口
    def get_news(self, days_of_news=-700, category=None):
        # 先查看缓存，一天内生效
        the_log = ELFBlog.objects.filter(regno=self.regno, ftype=1, code="200").order_by("-time").first()
        if the_log and (timezone.now() - the_log.time).days < 100:
            return json.loads(the_log.response)

        endtime = int(time.time())
        begintime = int(time.mktime((datetime.datetime.now() + datetime.timedelta(days=days_of_news)).timetuple()))
        the_url = self.the_host + "company/%s/event?begin=%s&end=%s&apikey=%s" % (self.regno, begintime, endtime, self.the_key)
        if category is not None:
            the_url += "&category=%s" % category
        result, status_code, response, hits = [], "", "", 0
        try:
            r = requests.get(the_url, timeout=15)
            status_code, response = r.status_code, r.text
            if status_code in ["200", "201", 200, 201]:
                result = json.loads(response)
                hits = result["event"]["total"]
        except Exception:
            add_log.info("FB news 502 with regno: %s\n\n.", self.regno)
        except requests.exceptions.Timeout:
            add_log.info("FB news Timeout with regno: %s\n\n.", self.regno)
        # 记录API调用日志
        ELFBlog.objects.create(regno=self.regno, ftype=1, code=status_code, hits=hits, request=the_url, response=response)
        return result

    # 招投标接口
    def get_bid(self, the_from=0, the_size=50):
        # 先查看缓存，一周内生效
        the_log = ELFBlog.objects.filter(regno=self.regno, ftype=2, code="200").order_by("-time").first()
        if the_log and (timezone.now() - the_log.time).days < 300:
            return json.loads(the_log.response)

        the_url = self.the_host + "company/%s/ztb?apikey=%s&from=%s&size=%s" % (self.regno, self.the_key, the_from, the_size)
        result, status_code, response, hits = [], "", "", 0
        try:
            r = requests.get(the_url, timeout=15)
            status_code, response = r.status_code, r.text
            if status_code in ["200", "201", 200, 201]:
                result = json.loads(response)
                hits = result["total"]
        except Exception:
            add_log.info("FB ztb 502 with regno: %s\n\n.", self.regno)
        except requests.exceptions.Timeout:
            add_log.info("FB ztb Timeout with regno: %s\n\n.", self.regno)
        # 记录API调用日志
        ELFBlog.objects.create(regno=self.regno, ftype=2, code=status_code, hits=hits, request=the_url, response=response)
        return result

    # 土地接口
    def get_land(self, the_from=0, the_size=50):
        # 先查看缓存，一月内生效
        the_log = ELFBlog.objects.filter(regno=self.regno, ftype=3, code="200").order_by("-time").first()
        if the_log and (timezone.now() - the_log.time).days < 300:
            return json.loads(the_log.response)

        the_url = self.the_host + "company/%s/tudi?apikey=%s&from=%s&size=%s" % (self.regno, self.the_key, the_from, the_size)
        result, status_code, response, hits = [], "", "", 0
        try:
            r = requests.get(the_url, timeout=15)
            status_code, response = r.status_code, r.text
            if status_code in ["200", "201", 200, 201]:
                result = json.loads(response)
                hits = result["total"]
        except Exception:
            add_log.info("FB tudi 502 with regno: %s\n\n.", self.regno)
        except requests.exceptions.Timeout:
            add_log.info("FB tudi Timeout with regno: %s\n\n.", self.regno)
        # 记录API调用日志
        ELFBlog.objects.create(regno=self.regno, ftype=3, code=status_code, hits=hits, request=the_url, response=response)
        return result

    # 著作权接口
    def get_zzq(self, the_from=0, the_size=50):
        # 先查看缓存，一月内生效
        the_log = ELFBlog.objects.filter(regno=self.regno, ftype=4, code="200").order_by("-time").first()
        if the_log and (timezone.now() - the_log.time).days < 300:
            return json.loads(the_log.response)

        the_url = self.the_host + "company/%s/zzq?apikey=%s&from=%s&size=%s" % (self.regno, self.the_key, the_from, the_size)
        result, status_code, response, hits = [], "", "", 0
        try:
            r = requests.get(the_url, timeout=15)
            status_code, response = r.status_code, r.text
            if status_code in ["200", "201", 200, 201]:
                result = json.loads(response)
                hits = result["total"]
        except Exception:
            add_log.info("FB zzq 502 with regno: %s\n\n.", self.regno)
        except requests.exceptions.Timeout:
            add_log.info("FB zzq Timeout with regno: %s\n\n.", self.regno)
        # 记录API调用日志
        ELFBlog.objects.create(regno=self.regno, ftype=4, code=status_code, hits=hits, request=the_url, response=response)
        return result

    # ICP接口
    def get_icp(self, the_from=0, the_size=50):
        # 先查看缓存，四周内生效
        the_log = ELFBlog.objects.filter(regno=self.regno, ftype=5, code="200").order_by("-time").first()
        if the_log and (timezone.now() - the_log.time).days < 300:
            return json.loads(the_log.response)

        the_url = self.the_host + "company/%s/icp?apikey=%s&from=%s&size=%s" % (self.regno, self.the_key, the_from, the_size)
        result, status_code, response, hits = [], "", "", 0
        try:
            r = requests.get(the_url, timeout=15)
            status_code, response = r.status_code, r.text
            if status_code in ["200", "201", 200, 201]:
                result = json.loads(response)
                hits = result["total"]
        except Exception:
            add_log.info("FB icp 502 with regno: %s\n\n.", self.regno)
        except requests.exceptions.Timeout:
            add_log.info("FB icp Timeout with regno: %s\n\n.", self.regno)
        # 记录API调用日志
        ELFBlog.objects.create(regno=self.regno, ftype=5, code=status_code, hits=hits, request=the_url, response=response)
        return result


# 文木源的api类
class WmyAPI(object):
    the_key = "dfs3erUUofeLSnvcxer9"
    company_name, sign = "", ""

    def __init__(self, company_name):
        sha = hashlib.md5()
        sha.update((company_name + self.the_key).encode("utf8"))
        self.sign = sha.hexdigest()
        self.company_name = company_name

    def __str__(self):
        return 'WMY API'

    # 招聘接口
    def get_zp(self, ztype=101):
        host = "http://139.129.219.66/sqapi/jobs/"
        # 默认 招聘职位列表
        if ztype == 102:
            # 招聘公司详细信息
            host += 'getintro/'
        elif ztype == 103:
            # 招聘公司薪酬分布
            host += 'getsalary/'
        elif ztype == 104:
            # 招聘公司其它分布
            host += 'getratio/'
        return self.base_api(host, ztype)

    # 招投标接口
    def get_bid(self):
        ftype = 2
        host = "http://114.215.96.52/interface/bid/"
        return self.base_api(host, ftype)

    # ICP接口
    def get_icp(self, company_url=None):
        ftype = 301
        if company_url:
            # 网站信息
            host = 'http://123.57.208.103:8000/icp_info/'
        else:
            # 网站运营
            ftype = 302
            host = "http://123.57.208.103:8000/icp_url/"
        return self.base_api(host, ftype, company_url=company_url)

    # 税务违法违规信息
    def get_tax(self):
        ftype = 4
        host = "http://123.57.208.103:8000/tax/"
        return self.base_api(host, ftype)

    # 环保违法违规信息
    def get_env(self):
        ftype = 5
        host = "http://123.57.208.103:8000/env/"
        return self.base_api(host, ftype)

    # 土地接口
    def get_land(self):
        ftype = 6
        host = "http://123.57.208.103:8000/land/"
        return self.base_api(host, ftype)

    # 住房建设信息
    def get_cons(self):
        ftype = 7
        host = "http://123.57.208.103:8000/cons/"
        return self.base_api(host, ftype)

    # 房产信息
    def get_prop(self):
        ftype = 8
        host = "http://123.57.208.103:8000/prop/"
        return self.base_api(host, ftype)

    # 教育部信息
    def get_edu(self, stype=901):
        host = "http://123.57.208.103:8000/edu/"
        if stype == 901:
            host += 'school_common/'
        elif stype == 9022:
            host += 'school_adult/'
        return self.base_api(host, stype, kw='school_name')

    # 质检信息
    def get_qa(self):
        ftype = 10
        host = "http://123.57.208.103:8000/qa/"
        return self.base_api(host, ftype)

    # 海关信息
    def get_cust(self):
        ftype = 11
        host = "http://123.57.208.103:8000/cust_data/"
        return self.base_api(host, ftype)


    def base_api(self, url, ftype, kw='company_name', company_url=None):
        # 先查看缓存，一周内生效
        the_log = ELWmylog.objects.filter(company_name=self.company_name, ftype=ftype, code="200").order_by("-time").first()
        if the_log and (timezone.now() - the_log.time).days < 7:
            if the_log.response != "COMPANY_NOT_FOUND":
                return json.loads(the_log.response)
            else:
                return []

        the_url = url + "?sign=%s&%s=%s" % (self.sign, kw, self.company_name)
        if company_url:
            the_url += '&url=%s' % (company_url)
        result, status_code, response, hits = [], "", "", 0
        try:
            r = requests.get(the_url, timeout=15)
            status_code, response = r.status_code, r.text
            if status_code in ["200", "201", 200, 201] and response != "COMPANY_NOT_FOUND":
                result = json.loads(response)
                hits = len(result)
        except Exception:
            add_log.info("FB news 502 with regno: %s\n\n.", self.company_name)
        except requests.exceptions.Timeout:
            add_log.info("FB news Timeout with regno: %s\n\n.", self.company_name)
        # 记录API调用日志
        ELWmylog.objects.create(company_name=self.company_name, ftype=ftype, code=status_code, hits=hits, request=the_url, response=response)
        return result
